package com.fare.fdc.action;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.stereotype.Controller;

import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.thread.CELineThread;
import com.fare.taluo.core.domain.thread.CSAirLineThread;
import com.fare.taluo.core.domain.thread.HNLinePdfParseThread;
import com.fare.taluo.core.domain.thread.MFAirLineThread;
import com.fare.taluo.core.domain.thread.ThreadFlag;
import com.fare.taluo.core.domain.thread.ZHLinePdfParseThread;
import com.fare.taluo.util.JsonUtil;
import com.fare.taluo.util.StringUtils;
import com.fare.taluo.vo.core.SourceEntityVO;
import com.fare.taluo.vo.core.SourceTempVO;


@Controller("parseAction")
public class ParseAction extends BaseFdcAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8594461049232515476L;
	private  List<SourceEntityVO>  sourceLists;
	@Resource(name="sourceApplication")
	private SourceApplication sourceApplication;
	private String carrierKey;
	public String toAnalyseJSP() {
		returnPageURL = "/fare/pdfParse.jsp";
		return "dispatcher";
	}
	public void getSource() throws JsonGenerationException, JsonMappingException, IOException{
		sourceLists = sourceApplication.findSourceEntityListByConditions("","","","",1,1000);
	    List<SourceTempVO> list = new ArrayList<SourceTempVO>();
	    for (Iterator iterator = sourceLists.iterator(); iterator.hasNext();) {
			SourceEntityVO vo = (SourceEntityVO) iterator.next();
			if(!vo.getName().equals("淘宝旅游网")&&!vo.getName().equals("去哪儿网") && !vo.getName().contains("携程") && !vo.getName().contains("艺龙")){
				SourceTempVO temp = new SourceTempVO();
				temp.setCompanyName(vo.getName());
				temp.setCarrierKey(vo.getCarrierKey());
				list.add(temp);
			}
			
		}
		try {
			String data =  this.toJSON(list, list.size());
			super.toJSONOut(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public String toJSON(List list,int total) throws JsonGenerationException, JsonMappingException, IOException{
		String jsonStr = "{\"Total\":"+total+","+
						 "\"Rows\":";
		int i = 0;
		String json = JsonUtil.toJson(list);
		jsonStr += json;
		jsonStr += "}";
		return jsonStr;
	}
	
	public void autoParse() throws InterruptedException{
		
		if(StringUtils.isNotEmpty(carrierKey)){
			ExecutorService service = Executors.newFixedThreadPool(3);
			if("HU".equalsIgnoreCase(carrierKey)){
				service.execute(new HNLinePdfParseThread()); 
				//com.kit.utils.JsonUtil.sendMessage("{\"result\":\"解析成功!\"}");
			}else if("MU".equalsIgnoreCase(carrierKey)){
				this.muParse();
				//this.sendMessage();
				//com.kit.utils.JsonUtil.sendMessage("{\"result\":\"解析成功!\"}");
			}else if("CZ".equalsIgnoreCase(carrierKey)){
				this.czParse();
			}else if("MF".equalsIgnoreCase(carrierKey)){
				this.mfParse();
			}else if("ZH".equalsIgnoreCase(carrierKey)){
				service.execute(new ZHLinePdfParseThread()); 
				//com.kit.utils.JsonUtil.sendMessage("{\"result\":\"解析成功!\"}");
			}else if("CA".equalsIgnoreCase(carrierKey)){
				//break;
			}
			
			service.shutdown();
			
			this.sendMessage();
			
		}
			
		
	}
	private void sendMessage(){
		HttpServletResponse response = ServletActionContext.getResponse();
		Writer out;
		try {
			out = response.getWriter();
			out.write("OK");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*HttpServletResponse response = ServletActionContext.getResponse();
		Writer out;
		try {
			out = response.getWriter();
			out.write("OK");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		while(true){
			
			if(ThreadFlag.isFinish){
				ThreadFlag.setIsFinish(false);
				com.kit.utils.JsonUtil.sendMessage("{\"result\":\"解析成功!\"}");
				break;
			}
		}*/
	}
	/**
	 * 东航的网上解析
	 * @throws InterruptedException 
	 */
	private void muParse() throws InterruptedException{
		int count = 0,sum=0;
		//1获得所有机场信息
		PortEntity portEntity = new PortEntity();
		//获得所有机场
		List<PortEntity> portList =  portEntity.findAll();	
		//2循环拼装成 xxx-xxx 形式
		List<String> portCodes = new ArrayList<String>();
		for (Iterator iterator = portList.iterator(); iterator.hasNext();) {
			PortEntity portEntity1 = (PortEntity) iterator.next();
			for (Iterator iterator2 = portList.iterator(); iterator2.hasNext();) {
				PortEntity portEntity2 = (PortEntity) iterator2.next();
				portCodes.add(portEntity1.getCode()+"-"+portEntity2.getCode());
			}
		}		
		int threadCount =20;//设置线程数量
		CountDownLatch threadsSignal = new CountDownLatch(threadCount);
		int count1 = portCodes.size()/threadCount;
		ExecutorService service = Executors.newFixedThreadPool(threadCount);
		 for(int i=0;i<threadCount;i++){
			 if(i==(threadCount-1)){
				 service.execute(new CELineThread(portCodes.subList(i*count1,count1*(i+1)+1),threadsSignal));
			 }else{
				 service.execute(new CELineThread(portCodes.subList(i*count1,count1*(i+1)),threadsSignal));	
			 }
	     }
		 service.shutdown();
		 threadsSignal.await();
		/* while(true){
			 if(ThreadFlag.isFinish){
					ThreadFlag.setIsFinish(false);
					com.kit.utils.JsonUtil.sendMessage("{\"result\":\"解析成功!\"}");
					break;
				}
		 }*/
	}
	/**
	 * 厦航的网上解析
	 */
	private void mfParse(){
		int count = 0,sum=0;
		//1获得所有机场信息
		PortEntity portEntity = new PortEntity();
		//获得所有机场
		List<PortEntity> portList =  portEntity.findAll();	
		//2循环拼装成 xxx-xxx 形式
		List<String> portCodes = new ArrayList<String>();
		for (Iterator iterator = portList.iterator(); iterator.hasNext();) {
			PortEntity portEntity1 = (PortEntity) iterator.next();
			portCodes.add(portEntity1.getCode());
			
			/*for (Iterator iterator2 = portList.iterator(); iterator2.hasNext();) {
				PortEntity portEntity2 = (PortEntity) iterator2.next();
				portCodes.add(portEntity1.getPortCode()+"-"+portEntity2.getPortCode());
			}*/
		}	
		
		/*
		//test不用线程执行
		
		//加载配置文件
		//系统默认的config.properties配置文件
		ConfigContainer.getInstance().register(DefaultPropertiesLoader.class);
		//hbase数据库配置文件(可以改为像jdbc.properties文件一样由spring加载)
		ConfigContainer.getInstance().register(HBasePropertiesLoader.class);
		//抓取数据相关配置
		ConfigContainer.getInstance().register("com.fare.taluo.core.domain.crawl.CrawlPropertiesLoader");
		
//		PortEntity portEntity = new PortEntity();
		FlightInfoEntity entity = new FlightInfoEntity();
//		List<PortEntity> portList =  portEntity.findAllPortEntity();//获得所有机场
		Map<String,PortEntity> map = portEntity.findPortEntityToMapByName();//以map的形式保存机场 key:机场中文名称
		
		//3循环去访问网站尝试
		for (Iterator iterator = portCodes.iterator(); iterator.hasNext();) {
			String string = (String) iterator.next();
			String[] codes = string.split("-");
			String fromCityCode = codes[0];
			String toCityCode = codes[1];
			
			//抓取机场模型
			CrawlCSAirLineModel portModel = new CrawlCSAirLineModel();
			portModel.setFromCity(fromCityCode);
			portModel.setToCity(toCityCode);
			MFAirLineAdaptor adap = new MFAirLineAdaptor(portModel);
			List<Object>  obj = null;
//			int fetchCount = PropertyUtils.getIntProperty("crawl.line.fail.repeat.times", CrawlPropertiesLoader.CONFIG_FILE);
			try{
//				while(fetchCount > 0){
				obj = adap.fetch(null);
//			    fetchCount--;	
				    if(obj.size()>0){
//				    	System.out.println("----running---- "+this.getName()+" "+(++sum));
				    	//循环执行，存入数据库中
				    	for (Iterator iterator2 = obj.iterator(); iterator2.hasNext();){
				    		FlightInfoVO vo=(FlightInfoVO) iterator2.next();
				    		entity.setEntryTime(new Date());
				    		entity.setCompanyCode("MF");
				    		entity.setCompanyName("厦门航空");
				    		entity.setFromCityName(vo.getFromCityName());
				    		entity.setToCityName(vo.getToCityName());
				    		entity.setEffectEndTime(vo.getEffectEndTime());
				    		entity.setEffectStartTime(vo.getEffectStartTime());
				    		entity.setFlightNo(vo.getFlightNo());
				    		entity.setStopCity(vo.getStopCity());
				    		
				    		entity.tranSave(entity);
				    		
				    		System.out.println("+++保存++++++++++++++++++++++++++++++++++");
				    	}
				    	
//				    }
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
			
		}
		
	*/	
		
		
		//下面是厦航的线程
		//开多线程去尝试
		int threadCount3 = 10;//设置线程数量
		int count2 = portCodes.size()/threadCount3;
		ExecutorService service3 = Executors.newFixedThreadPool(threadCount3);
			for(int i=0;i<threadCount3;i++){
			 if(i==(threadCount3-1)){
				 service3.execute(new MFAirLineThread(portCodes.subList(i*count2,count2*(i+1)+1)));
			 }else{
				 service3.execute(new MFAirLineThread(portCodes.subList(i*count2,count2*(i+1))));	
			 }
	     }
		 service3.shutdown();
		 while(true){
			 if(ThreadFlag.isFinish){
					ThreadFlag.setIsFinish(false);
					super.toJSONOut("{\"result\":\"解析成功!\"}");
					break;
				}
		 }
	}
	/**
	 * 南航的网上解析
	 */
	private void czParse(){
		int count = 0,sum=0;
		//1获得所有机场信息
		PortEntity portEntity = new PortEntity();
		//获得所有机场
		List<PortEntity> portList =  portEntity.findAll();	
		//2循环拼装成 xxx-xxx 形式
		List<String> portCodes = new ArrayList<String>();
		for (Iterator iterator = portList.iterator(); iterator.hasNext();) {
			PortEntity portEntity1 = (PortEntity) iterator.next();
			for (Iterator iterator2 = portList.iterator(); iterator2.hasNext();) {
				PortEntity portEntity2 = (PortEntity) iterator2.next();
				portCodes.add(portEntity1.getCode()+"-"+portEntity2.getCode());
			}
		}		
		//下面是南航的线程
		//开多线程去尝试
		int threadCount2 = 10;//设置线程数量
		int count2 = portCodes.size()/threadCount2;
		ExecutorService service2 = Executors.newFixedThreadPool(threadCount2);
		 for(int i=0;i<threadCount2;i++){
			 if(i==(threadCount2-1)){
				 service2.execute(new CSAirLineThread(portCodes.subList(i*count2,count2*(i+1)+1)));
			 }else{
				 service2.execute(new CSAirLineThread(portCodes.subList(i*count2,count2*(i+1))));	
			 }
	     }
		 service2.shutdown();
		 while(true){
			 if(ThreadFlag.isFinish){
					ThreadFlag.setIsFinish(false);
					super.toJSONOut("{\"result\":\"解析成功!\"}");
					break;
				}
		 }
	}
	
	public static void main(String[] args) {
//		mfParse();
		System.out.println("success");
	}
	public List<SourceEntityVO> getSourceLists() {
		return sourceLists;
	}



	public void setSourceLists(List<SourceEntityVO> sourceLists) {
		this.sourceLists = sourceLists;
	}

	public String getCarrierKey() {
		return carrierKey;
	}
	public void setCarrierKey(String carrierKey) {
		this.carrierKey = carrierKey;
	}
}
